package com.ccb.jyzx.expand.tiantouonline.service.impl;

import com.ccb.jyzx.expand.tiantouonline.bean.FileInfo;
import com.ccb.jyzx.expand.tiantouonline.contant.StatusContant;
import com.ccb.jyzx.expand.tiantouonline.service.FileInfoService;
import com.ccb.jyzx.expand.tiantouonline.service.FileOpService;
import com.ccb.jyzx.expand.tiantouonline.utils.FileUploadUtils;
import com.ccb.jyzx.expand.tiantouonline.utils.ParseDateUtils;
import com.ccb.jyzx.expand.tiantouonline.view.request.FsUploadFileInfoRequest;
import com.ccb.jyzx.expand.tiantouonline.view.request.FsUploadFileRespons;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * @author XIEFEI
 * @date 2019-11-18 16:29
 * @Description
 **/
@Service
public class FileOpServiceImpl implements FileOpService {
//    @Value("${nas_home_path}")
  //  public String nasPath;

    @Value("${file_cache_dir}")
    public String file_cache_dir;

    Logger logger = LoggerFactory.getLogger(FileOpServiceImpl.class);

    @Autowired
    FileInfoService fileInfoService;

    @Override
    public FsUploadFileRespons saveFile(FsUploadFileInfoRequest fileInfo, HttpServletResponse response) {
      FileInfo info= fileInfoService.getById(fileInfo.getFileId());

      if (info==null){
          return new FsUploadFileRespons("上传错误:fileId值不合法!",StatusContant.ERROR_CODE,null);
      }

        //解析16进制文件块
        try {
            byte[] bytes = FileUploadUtils.hexToByte(fileInfo.getUpfile());
            //生成文件存储目录
            File cachDir = new File(file_cache_dir);
            if (!cachDir.exists()){
                cachDir.mkdirs();
            }
            File tagetFileDir= new File(cachDir,info.getSavePath());
            if (!tagetFileDir.exists()){
                tagetFileDir.mkdirs();
            }
            File tagetFile= new File(tagetFileDir,fileInfo.getBlockId());
            tagetFile.setExecutable(false);
            tagetFile.setReadable(true);
            tagetFile.setWritable(true);

          return  saveFileBlock(tagetFile,bytes,fileInfo,response);


        }catch (Exception e){
            e.printStackTrace();
            return new FsUploadFileRespons("上传失败:解析16进制块文件字符串时发生错误", StatusContant.ERROR_CODE,null);
        }
    }

    private FsUploadFileRespons saveFileBlock(File tagetFile, byte[] upfile, FsUploadFileInfoRequest fileInfo,HttpServletResponse response) {
        BufferedOutputStream out = null;
        try {
            if (tagetFile.exists()&&tagetFile.isFile()){
                tagetFile.delete();
            }
            out = new BufferedOutputStream(new FileOutputStream(tagetFile));

            out.write(upfile, 0, upfile.length);
            out.flush();
            String blockSize = fileInfo.getBlockSize();
            Long bs= Long.valueOf(blockSize);
            //已接收文件大小
            long reseverSize = tagetFile.length();
            if (reseverSize == bs) {
                //更新文件上传时间
                fileInfoService.updateUploadTime(fileInfo.getFileId(),ParseDateUtils.getFormateTimeLong());

                response.setStatus(200);
                return  new FsUploadFileRespons("块文件上传成功", StatusContant.OK_CODE,null);
            } else {
                logger.error("服务器异常:实际接收到的块大小为" + reseverSize + " 不等于上传参数blockSize的值:" + blockSize);
                response.setStatus(500);
                return new FsUploadFileRespons( "上传异常:实际接收到的块大小为" + reseverSize + " 不等于上传参数blockSize的值:" + blockSize, StatusContant.ERROR_CODE,null);
            }

        } catch (IOException e) {
            e.printStackTrace();
            response.setStatus(500);
            logger.error("文件接收发生异常:" + e.getMessage());
            return new FsUploadFileRespons("上传失败:后台接收发生异常", StatusContant.ERROR_CODE,null);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
